#pragma once
#include "TrTypes.h"
#include "ThostFtdcUserApiStruct.h"
#include "ThostFtdcMdApi.h"
#include "TrSingleton.h"
#include "EventEngine.h"
#include <memory>
#include <string>
#include <unordered_set>
#include <unordered_map>
#include <QObject>
#include <QLibrary>

namespace Market {

// CTP API创建函数类型定义
typedef CThostFtdcMdApi* (*CreateFtdcMdApiFunc)(const char*, bool, bool);

class MarketDataEngine : public QObject, public CThostFtdcMdSpi, public TrSingleton<MarketDataEngine> {
    Q_OBJECT
    friend class TrSingleton<MarketDataEngine>;
public:
    // 初始化和控制
    bool init(const QString& configFile);
    void start();
    void stop();
    
    // 订阅和取消订阅
    bool subscribe(const std::string& symbol);
    bool unsubscribe(const std::string& symbol);
    bool batchSubscribe(const std::vector<std::string>& symbols);
    bool batchUnsubscribe(const std::vector<std::string>& symbols);
    
    // 获取当前订阅列表
    std::vector<std::string> getSubscribedSymbols() const;
    
signals:
    // 连接状态信号
    void connected();                                    // 连接成功
    void disconnected(int reason);                      // 连接断开
    void loginSuccess();                                // 登录成功
    void loginFailed(const QString& error);             // 登录失败
    void error(int errorId, const QString& errorMsg);   // 错误信息
    
    // 行情数据信号
    void tickReceived(const WTSTickStruct& tick);       // 收到Tick数据
    
protected:
    // CTP回调实现
    void OnFrontConnected() override;
    void OnFrontDisconnected(int nReason) override;
    void OnHeartBeatWarning(int nTimeLapse) override;
    void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, 
                       CThostFtdcRspInfoField *pRspInfo, 
                       int nRequestID, 
                       bool bIsLast) override;
    void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, 
                        CThostFtdcRspInfoField *pRspInfo, 
                        int nRequestID, 
                        bool bIsLast) override;
    void OnRspError(CThostFtdcRspInfoField *pRspInfo, 
                   int nRequestID, 
                   bool bIsLast) override;
    void OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, 
                           CThostFtdcRspInfoField *pRspInfo, 
                           int nRequestID, 
                           bool bIsLast) override;
    void OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, 
                             CThostFtdcRspInfoField *pRspInfo, 
                             int nRequestID, 
                             bool bIsLast) override;
    void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) override;
    
private:
    explicit MarketDataEngine(QObject* parent = nullptr);
    ~MarketDataEngine();
    
    // 禁用拷贝和赋值
    MarketDataEngine(const MarketDataEngine&) = delete;
    MarketDataEngine& operator=(const MarketDataEngine&) = delete;
    
    // 加载CTP库
    bool loadCtpLibrary(const QString& configFile);
    
    // 登录请求
    void reqUserLogin();
    
    // 检查错误
    bool hasError(CThostFtdcRspInfoField *pRspInfo);
    
    // CTP API相关
    QLibrary m_ctpLibrary;                      // CTP动态库
    CreateFtdcMdApiFunc m_createApiFunc;        // 创建API函数指针
    CThostFtdcMdApi* m_pUserApi{nullptr};       // CTP API实例
    
    // 配置相关
    QString m_configPath;                        // 配置文件根路径
    QString m_brokerID;                         // 经纪商代码
    QString m_userID;                           // 用户ID
    QString m_password;                         // 密码
    QString m_frontAddr;                        // 前置机地址
    QString m_flowDir;                          // 流文件目录
    
    // 状态相关
    bool m_initialized{false};                   // 初始化标志
    bool m_isLoggedIn{false};                   // 登录状态
    int m_requestID{0};                         // 请求ID
    
    // 订阅管理
    std::unordered_set<std::string> m_subscribedSymbols;  // 已订阅的合约集合

    // 增量数据计算
    std::unordered_map<std::string, double> m_lastVolumes;      // 上次成交量
    std::unordered_map<std::string, double> m_lastTurnovers;    // 上次成交额
    std::unordered_map<std::string, double> m_lastOpenInterests;// 上次持仓量
};

#define MARKET_ENGINE Market::MarketDataEngine::instance()

} // namespace Market